﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Resources;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.Threading;

namespace Arch.Aspects
{
    public class EntityRequiredAttribute : ValidationAttribute
    {
        private static ResourceManager resourceManager = new ResourceManager("System.ComponentModel.DataAnnotations.Resources.DataAnnotationsResources", typeof(RequiredAttribute).Assembly);

        private string ResourceErrorMessage { get { return resourceManager.GetString("RequiredAttribute_ValidationError"); } }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value == null)
            {
                string propertyName = validationContext.DisplayName;
                string idPropertyName = validationContext.DisplayName + "Id";

                var idPropertyInfo = validationContext.ObjectType.GetProperty(idPropertyName);

                if (idPropertyInfo != null)
                {
                    var idValue = idPropertyInfo.GetGetMethod().Invoke(validationContext.ObjectInstance, new object[0]);
                    var defaultValue = Activator.CreateInstance(idPropertyInfo.PropertyType);

                    if (Equals(idValue, defaultValue))
                        return new ValidationResult(ResourceErrorMessage, new[] { propertyName, idPropertyName });
                }
                else
                    return new ValidationResult(ResourceErrorMessage, new[] { propertyName });
            }
            return ValidationResult.Success;
        }
    }
}
